/**
 * @class Aurora.Lov
 * @extends Aurora.TextField
 * <p>Lov 值列表组件.
 * @author njq.niu@hand-china.com
 * @constructor
 * @param {Object} config 配置对象. 
 */
$S.Lov = Ext.extend($S.ComboBox,{
    constructor: function(config) {
        this.isWinOpen = false;
        this.fetching = false;
        this.needFetch = true;
        this.context = config.context||'';
        $S.Lov.superclass.constructor.call(this, config);        
    },
    initComponent : function(config){
        $S.Lov.superclass.initComponent.call(this,config);
        this.plusTtrigger = this.wrap.child('div[stype=plusTrigger]');
        this.para = {};
        if(!Ext.isEmpty(this.lovUrl)){
            this.lovUrl = this.processParmater(this.lovUrl);
        }
    },
    processListener: function(ou){
        $S.Lov.superclass.processListener.call(this, ou);
        if(this.plusTtrigger)this.plusTtrigger[ou]('click',this.onPlusTriggerClick, this, {preventDefault:true});
    },
    processParmater:function(url){
        var li = url.indexOf('?')
        if(li!=-1){
            this.para = Ext.urlDecode(url.substring(li+1,url.length));
            return url.substring(0,li);
        } 
        return url;
    },
    initEvents : function(){
        $S.Lov.superclass.initEvents.call(this);
        this.addEvents(
        /**
         * @event beforefetch
         * fetch前事件.
         * @param {Aurora.Lov} lov 当前lov
         * @param {Object} o 查询参数. 
         */
        'beforefetch',
        /**
         * @event beforecommit
         * commit前事件.
         * @param {Aurora.Record} r1 当前lov绑定的Record
         * @param {Aurora.Record} r2 选中的Record. 
         */
        'beforecommit',
        /**
         * @event commit
         * commit事件.
         * @param {Aurora.Lov} lov 当前Lov组件.
         * @param {Aurora.Record} r1 当前lov绑定的Record
         * @param {Aurora.Record} r2 选中的Record. 
         */
        'commit',
        /**
         * @event beforetriggerclick
         * 点击弹出框按钮之前的事件。
         * @param {Aurora.Lov} lov 当前Lov组件.
         */
        'beforetriggerclick');
    },
    onTriggerClick : function(e){
    	e.stopEvent();
    	if(this.fireEvent('beforetriggerclick',this)){
            this.collapse();
    		this.showLovWindow();
    	}
    },
    setHeight: function(h){
        $S.Lov.superclass.setHeight.call(this, h);
        if(this.plusTtrigger)this.plusTtrigger.setStyle("height",(h-2)+"px");
    },
    setWidth: function(w){
        $S.Lov.superclass.setWidth.call(this,w);
        //if(this.plusTtrigger) this.el.setStyle("width",(w-52)+"px");
    }, 
    bind : function(ds, name){
        $S.Lov.superclass.bind.call(this,ds,name);
        this.processPlusTrigger(this.record)
    },
    onUpdate : function(ds, record, name, value){
        $S.Lov.superclass.onUpdate.call(this,ds, record, name, value);
        this.processPlusTrigger(record)
    },
    processPlusTrigger : function(record){
        var ptr = $S.getFunction(this.plusTriggerRenderer)
        if(ptr){
            ptr.call(window,this, record);
        }
    },
    showPlusTrigger : function(){
        if(this.plusTtrigger) {
            this.plusTtrigger.setStyle('display','');
            var w = this.wrap.getWidth();
            if(w-53>0)this.el.setStyle("width",(w-53)+"px");
        }
    },
    hidePlusTrigger : function(){
        if(this.plusTtrigger) {
            var w = this.wrap.getWidth();
            this.plusTtrigger.setStyle('display','none');
            if(w-30>0)this.el.setStyle("width",(w-30)+"px");
        }
    },
    onPlusTriggerClick : function(e){
        e.stopEvent();
        this.collapse();
        var pth = $S.getFunction(this.plusTriggerHandler);
        if(pth){
            pth.call(window,this);
        }
    },
    onBlur : function(e){
        var ov,nv;
        if(this.record) ov = this.record.get(this.binder.name); 
        $S.Lov.superclass.onBlur.call(this,e);
        nv = this.getRawValue();
        if(ov != nv && !Ext.isEmpty(this.fetchUrl))
            this.fetchRecord();
    },
    //改用onBlur 因为如果是用全角输入,好像就不触发change事件了
//    onChange : function(e){
//        if(this.fetchRemote == true)
//			this.fetchRecord();
//    },
    onKeyDown : function(e){
        if(this.isWinOpen)return; 
        $S.Lov.superclass.onKeyDown.call(this,e);
    },
    canHide : function(){
        return this.isWinOpen == false
    },
    close : function(){
        if(this.win) this.win.close();
    },
    hide : function(){
        this.win.hide();
    },
    show : function(){
        this.win.show();
    },
    commit:function(r,lr,mapping){
        this.close();
//        this.setRawValue('')
        var record = lr ? lr : this.record;
        if(record && r){
            this.fireEvent('beforecommit', this, record, r)
            var mapping = mapping || this.getMapping();
            for(var i=0;i<mapping.length;i++){
                var map = mapping[i];
//                record.set(map.to,r.get(map.from)||'');//如果是0,就为变成空
                record.set(map.to,r.get(map.from));
            }
        }
//        else{
//          this.setValue()
//        }
        
        this.fireEvent('commit', this, record, r)
    },
    getMapping: function(){
        var mapping
        if(this.record){
            var field = this.record.getField(this.binder.name);
            if(field){
                mapping = field.get('mapping');
            }
        }
        return mapping ? mapping : [{from:this.binder.name,to:this.binder.name}];
    },
    afterClose: function(){
        this.isWinOpen = false;
        this.win = null;
        if(!Ext.isIE6 && !Ext.isIE7){//不知什么地方会导致冲突,ie6 ie7 会死掉 
            this.focus();
        }else{
        	var sf = this;
        	setTimeout(function(){sf.focus()},10)	
        }
    },
    getLovPara : function(){
        var para = Ext.apply({},this.para);
        var field;
        if(this.record) field = this.record.getField(this.binder.name);
        if(field){
            var lovpara = field.get('lovpara'); 
            if(lovpara)Ext.apply(para,lovpara);
        }
        return para;
    },
    fetchRecord : function(){
        if(this.disabeld == true) return;
        this.fetching = true;
        var v = this.getRawValue(),url = this.fetchUrl;
        
//        if(!Ext.isEmpty(this.fetchUrl)){
//            url = this.context + 'svc/'+this.lovUrl+'/query&_ps=1&_pn=1&'+ Ext.urlEncode(this.getLovPara());
//        }
        var record = this.record;
        record.isReady=false;
        var p = {};
        
        var mapping = this.getMapping();
        for(var i=0;i<mapping.length;i++){
            var map = mapping[i];           
            if(this.binder.name == map.to){
                p[map.from]=v;
            }
            record.set(map.to,'');          
        }
        if(Ext.isEmpty(v)) {
            this.fetching = false;
            record.isReady=true;
            return;
        }
        if(this.fetchField) p[this.fetchField] = v;
        this.setRawValue('正在查询...');
        this.fireEvent('beforefetch', this, p)
        $S.request({url:url, para:p, success:function(res){
            var r = new $S.Record({});
            if(res.result){
                var datas = [].concat(res.result);
                var aft = $S.getFunction(this.processData);
                if(aft) datas = aft.call(window,p,datas);
                if(datas.length>0){
                    var data = datas[0];
                    r = new $S.Record(data);
                }
            }
            this.fetching = false;
            this.commit(r,record,mapping);
            record.isReady=true;
        }, error:this.onFetchFailed, scope:this});
    },
    onFetchFailed: function(res){
        this.fetching = false;
    },
    showLovWindow : function(){        
        if(this.fetching||this.isWinOpen||this.disabled) return;       
        var v = this.getRawValue();
        this.blur();
        var url,mapping = this.getMapping(),para ={};
        for(var i=0;i<mapping.length;i++){
            var map = mapping[i];
            if(map.para === "true"){
                para[map.to] = this.record.get(map.to);
            }
        }
        para = Ext.apply(para,this.getLovPara());        
        var lp = Ext.urlEncode(para);
        if(!Ext.isEmpty(this.lovUrl)){
            url = this.lovUrl+'?' +lp;
        }
        if(url) {
	        this.isWinOpen = true;
            this.win = new $S.Window({title:this.title||'Lov', url:url+ (lp!='' ? '&' : '') + "_lid="+this.id+"&key="+encodeURIComponent(v),height:this.lovHeight||400,width:this.lovWidth||400});
            this.win.on('close',this.afterClose,this);
        }
    },
    onInputClick : function(e){}
});
